import Vue from 'vue'
import Loading from './Loading.vue'
import { addClass, removeClass } from '@/utils'
const Mask = Vue.extend(Loading)

const toggleLoading = (el, binding) => {
  if (binding.value) {
    el.instance.visible = true
    // nextTick 保证 DOM 可用
    Vue.nextTick(() => {
      if (binding.modifiers.fullscreen) {
        addClass(el.mask, 'is-fullscreen')
        insertDom(document.body, el, binding)
      } else {
        removeClass(el.mask, 'is-fullscreen')
        insertDom(el, el, binding)
      }
    })
  } else {
    el.instance.visible = false
  }
}

const insertDom = (parent, el) => {
  parent.appendChild(el.mask)
}

const directive = {
  name: 'loading',
  hooks: {
    bind (el, binding, vnode) {
      // 提取特定 attr 属性的值
      const textExr = el.getAttribute('m-loading-text')
      const spinnerExr = el.getAttribute('m-loading-spinner')
      const backgroundExr = el.getAttribute('m-loading-background')
      const verticalExr = el.getAttribute('m-loading-vertical')
      const customClassExr = el.getAttribute('m-loading-custom-class')
      // 取得 el 的组件实例
      const vm = vnode.context
      // 完成 loading 组件的初始化操作
      const mask = new Mask({
        el: document.createElement('div'),
        data: {
          // 值有可能是 vm 的一个的属性名，先尝试读取
          text: (vm && vm[textExr]) || textExr,
          spinner: (vm && vm[spinnerExr]) || spinnerExr,
          background: (vm && vm[backgroundExr]) || backgroundExr,
          vertical: (vm && vm[verticalExr]) || verticalExr,
          customClass: (vm && vm[customClassExr]) || customClassExr,
          fullscreen: !!binding.modifiers.fullscreen
        }
      })
      el.instance = mask // 将 loading 组件实例拷贝到 el 下
      el.mask = mask.$el // 而组件实例的 HTML 节点拷贝为 mask 属性
      // 把 loading 添加到 DOM 的操作抽离为 toggleLoading，当移除时也可调用
      binding.value && toggleLoading(el, binding)
    },

    update (el, binding) {
      if (binding.oldValue !== binding.value) {
        // console.log('change value, now toggle loading!')
        toggleLoading(el, binding)
      }
    },

    unbind (el) {}
  }
}

const Plugin = {
  install (Vue) {
    // 注册指令
    Vue.directive(directive.name, directive.hooks)
    // todo: 添加全局方法
  }
}

export default Plugin
